from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from app.core.config import settings
from fastapi.middleware.cors import CORSMiddleware
from app.middleware.error_handler import error_handler_middleware
from app.core.logger import setup_logger
from app.api.v1.api import api_router
from app.core.database import init_db, close_db
from app.core.commands import run_migrations
import logging

logger = setup_logger(__name__, "app.log")

def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.VERSION,
        debug=settings.DEBUG,
        openapi_url=f"{settings.API_V1_STR}/openapi.json",
        docs_url=f"{settings.API_V1_STR}/docs",  # Swagger UI 地址
        redoc_url=f"{settings.API_V1_STR}/redoc",  # ReDoc 地址
        terms_of_service="http://example.com/terms/",
        contact={
            "name": "AI Tech Team",
            "url": "http://example.com/contact/",
            "email": "contact@example.com",
        },
        license_info={
            "name": "Apache 2.0",
            "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
        },
    )
    
    # 配置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 添加错误处理中间件
    app.middleware("http")(error_handler_middleware)
    
    # 注册数据库
    register_tortoise(
        app,
        db_url=settings.DATABASE_URL,
        modules={"models": ["app.models"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
    
    # 注册路由
    app.include_router(api_router, prefix=settings.API_V1_STR)
    
    @app.on_event("startup")
    async def startup_event():
        logger.info("Starting up...")
        await init_db(generate_schemas=True)
        # 自动执行数据库迁移
        try:
            await run_migrations()
            logger.info("Database migrations completed successfully")
        except Exception as e:
            logger.error(f"Error running migrations: {str(e)}")
            # 不抛出异常，允许应用继续启动
    
    @app.on_event("shutdown")
    async def shutdown_event():
        logger.info("Shutting down...")
        await close_db()
    
    return app

app = create_app()

@app.get("/", 
    tags=["Root"],
    summary="根路径",
    description="返回欢迎消息",
    response_description="欢迎消息"
)
async def root():
    """
    根路径接口
    
    返回一个简单的欢迎消息
    """
    return {"message": "Welcome to FastAPI"} 